// store/modules/cart.js
const state = () => ({
    items: [],
    currentSaveId: null,
});

const mutations = {
    ADD_TO_CART(state, payload) {
        if (payload.saveId) {
            // If we have a saveId, update the existing design
            const index = state.items.findIndex(item =>
                item.id === payload.saveId || item.saveId === payload.saveId
            );
            if (index !== -1) {
                // Update existing item but preserve its original ID
                const originalId = state.items[index].id;
                state.items.splice(index, 1, {
                    ...payload,
                    id: originalId,
                    saveId: originalId
                });
            } else {
                // If not found (shouldn't happen), add as new
                state.items.push(payload);
            }
        } else {
            // Add new design
            state.items.push(payload);
        }
        state.currentSaveId = null; // Reset current save ID after saving
    },
    REMOVE_FROM_CART(state, id) {
        state.items = state.items.filter(item => item.id !== id);
        if (state.currentSaveId === id) {
            state.currentSaveId = null;
        }
    },
    SET_CURRENT_SAVE_ID(state, saveId) {
        state.currentSaveId = saveId;
    },
    UPDATE_QUANTITY(state, { id, quantity }) {
        const item = state.items.find(item => item.id === id);
        if (item) {
            item.quantity = Math.max(1, quantity);
        }
    },
};

const actions = {
    addToCart({ commit }, payload) {
        commit('ADD_TO_CART', payload);
    },
    removeFromCart({ commit }, id) {
        commit('REMOVE_FROM_CART', id);
    },
    setCurrentSaveId({ commit }, saveId) {
        commit('SET_CURRENT_SAVE_ID', saveId);
    },
    updateQuantity({ commit }, payload) {
        commit('UPDATE_QUANTITY', payload);
    },
};

const getters = {
    cartItems: state => state.items,
    currentSaveId: state => state.currentSaveId,
    cartTotal: state => state.items.reduce((total, item) => total + (item.design.price * item.quantity), 0),
    cartItemCount: state => state.items.reduce((count, item) => count + item.quantity, 0),
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
};